﻿using AutoMapper;
using B.MES.Customer.Domain;
using B.MES.Customer.Domain.DTO;
using B.MES.Customer.Infrastructure.IRepository;
using CSRedis;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Yitter.IdGenerator;

namespace B.MES.Customer.Infrastructure.Repository
{
    /// <summary>
    /// RBAC仓储实现层
    /// </summary>
    public class RBACRepository : BaseRepository<User>, IRBACRepository
    {
        /// <summary>
        /// 用于连接和操作数据库接口
        /// </summary>
        private readonly ISqlSugarClient _db;
        CSRedis.CSRedisClient csredis;
        private readonly IMapper mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db">用于连接和操作数据库接口</param>
        public RBACRepository(ISqlSugarClient db, IMapper mapper) : base(db)
        {
            _db = db;
            csredis = new CSRedis.CSRedisClient("10.31.59.13");
            this.mapper = mapper;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="loginInput">包含用户名和密码的登录信息</param>
        /// <returns>根据用户名查询到的用户信息</returns>
        public APIResult<OutPutLogin> UserLogin(InputLogin loginInput)
        {
            APIResult<OutPutLogin> aPIResult = new APIResult<OutPutLogin>();

            try
            {
                var user = _db.Queryable<User>().Where(u => u.User_Name == loginInput.User_Name).First();
                if (user != null && user.User_PassWord == GetMD5Hash(loginInput.User_PassWord))
                {
                    OutPutLogin outPutLogin = new OutPutLogin()
                    {
                        User_Id = user.User_Id,
                        User_Name = user.User_Name,
                        U_Name = user.U_Name,
                        Job_number = user.Job_number,
                        User_Phone = user.User_Phone
                    };
                    //var random = new Random();
                    //var time = random.Next(10, 20);

                    // 这里的csredis是你的一个Redis操作对象，需要根据实际情况调整
                    csredis.Set("LoginInfo", outPutLogin);

                    aPIResult.Success(outPutLogin);
                    return aPIResult;
                }
                else
                {
                    aPIResult.Code = 400;
                    aPIResult.Message = "登录失败";
                    return aPIResult;
                }
            }
            catch (Exception ex)
            {
                aPIResult.Code = 500; // 代表服务器内部错误
                aPIResult.Message = "登录方法出错：" + ex.Message;
                return aPIResult;
            }
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="Password">需要加密的密码</param>
        /// <returns>加密之后的密码</returns>
        public object GetMD5Pwd(string Password)
        {
            return GetMD5Hash(Password);
        }

        /// <summary>
        /// 用户查询+分页+显示
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public PageApiResut<User> GetUserListByKeyword(string? user_Name, string? u_Name, int page, int size)
        {
            PageApiResut<User> pageApiResut=new PageApiResut<User>();

            var count = _db.Queryable<User>().Where(u => u.IsDelete == false).Count(); // 获取总记录数

            var userList = _db.Queryable<User>()
                    .WhereIF(!string.IsNullOrEmpty(user_Name), u => u.User_Name.Contains(user_Name))
                    .WhereIF(!string.IsNullOrEmpty(u_Name), u => u.U_Name.Contains(u_Name))// 根据用户名和姓名模糊查询
                    .Where(u => u.IsDelete == false)// 排除已经删除的用户
                    .ToPageList(page, size).ToList();

            pageApiResut.TotalCount = count;
            pageApiResut.Data = userList;

            return pageApiResut;
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="input">需要加密的密码</param>
        /// <returns>加密之后的密码</returns>
        static string GetMD5Hash(string input)
        {
            using (MD5 md5Hash = MD5.Create())
            {
                byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
                StringBuilder sBuilder = new StringBuilder();

                for (int i = 0; i < data.Length; i++)
                {
                    sBuilder.Append(data[i].ToString("x2"));
                }

                return sBuilder.ToString();
            }
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="requestUserDTO"></param>
        /// <returns></returns>
        public APIResult<RequestUserDTO> AddUser(RequestUserDTO requestUserDTO)
        {
            APIResult<RequestUserDTO> aPIResult = new APIResult<RequestUserDTO>();
            try
            {
                var id = DateTime.Now.ToString("yyyyMMddhhmmss");

                string pwd = requestUserDTO.User_PassWord;
                var addUser = mapper.Map<User>(requestUserDTO);
                addUser.User_Id = id;
                addUser.User_PassWord = GetMD5Hash(pwd);

                // 插入新用户信息
                _db.Insertable(addUser).ExecuteCommand();

                foreach (var item in requestUserDTO.ids.Split(','))
                {
                    User_Role user_Role = new User_Role();
                    user_Role.User_Id = id;
                    user_Role.Role_Id = item;
                    _db.Insertable(user_Role).ExecuteCommand();
                }

                // 查询最新添加的用户数据
                var newestUser = _db.Queryable<User>().OrderBy(u => u.User_Id, OrderByType.Desc).First();

                aPIResult.Success();
                if (newestUser != null)
                {
                    aPIResult.Data = mapper.Map<RequestUserDTO>(newestUser);
                }

                return aPIResult;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 获取所有角色
        /// </summary>
        /// <returns></returns>
        public List<Role> GetRole()
        {
            try
            {
                PageApiResut<Role> pageApiResut = new PageApiResut<Role>();
                var result = _db.Queryable<Role>().ToList();
                pageApiResut.TotalCount = result.Count;
                pageApiResut.Data = result;
                return result;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 单个删除（真删除）
        /// </summary>
        /// <param name="user_Id"></param>
        /// <returns></returns>
        public APIResult<User> UserDeleteData(string user_Id)
        {
            try
            { 
                APIResult<User> aPIResult = new APIResult<User>();
                _db.Deleteable<User>(user_Id).ExecuteCommand();
                aPIResult.SuccessDel();
                return aPIResult;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public APIResult<List<User>> BatchDeleteData(List<User> list)
        {
            APIResult<List<User>> apiResult = new APIResult<List<User>>();

            try
            {
                // 遍历传入的用户列表，更新每个用户对象的 IsDelete 属性为 true
                foreach (var user in list)
                {
                    user.IsDelete = true;
                }

                // 使用 SqlSugar 的 Updateable 方法批量更新用户对象列表
                _db.Updateable(list).ExecuteCommand();

                // 更新成功后将更新过的用户列表添加到 APIResult 对象中并返回
                apiResult.SuccessDel();
                return apiResult;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 显示菜单
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public List<MemuDTO> GetMemus(string userId)
        {
            var list = _db.Queryable<User_Role>().InnerJoin<Role_Permission>((ur, rp) =>
            ur.Role_Id==rp.Role_Id).InnerJoin<Permission>((ur, rp,p)=> rp.Permission_Id==p.Permission_Id).Where((ur, rp, p) => ur.User_Id == userId) // 根据实际情况修改条件
              .Select((ur, rp, p) => new Permission
              {
                  Pid = p.Pid,
                  Permission_Name = p.Permission_Name,
                  Permission_Id = p.Permission_Id,
                  MenuUrl = p.MenuUrl,
                  Icon = p.Icon,
              }).Distinct().ToList();
            return GetMemu(list, "0");
        }

        /// <summary>
        /// 显示全部菜单
        /// </summary>
        /// <param name="userId"></param> 
        /// <returns></returns>
        public List<MemuDTO> GetMemus()
        {
            var permissionList = _db.Queryable<Permission>().ToList();
            return GetMemu(permissionList, "0");
        }

        /// <summary>
        /// 递归菜单
        /// </summary>
        /// <param name="list"></param>
        /// <param name="pId"></param>
        /// <returns></returns>
        private List<MemuDTO> GetMemu(IEnumerable<Permission> list, string pId)
        {
            try
            {
                return list.Where(x => x.Pid == pId).Select(x => new MemuDTO
                {
                    Icon = x.Icon,
                    MenuUrl = x.MenuUrl,
                    Permission_Id = x.Permission_Id,
                    Permission_Name = x.Permission_Name,
                    Pid = x.Pid,
                    children = GetMemu(list, x.Permission_Id)
                }).ToList();
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="requestUserDTO"></param>
        /// <returns></returns>
        public APIResult<RequestUserDTO> UpdateUser(RequestUserDTO requestUserDTO)
        {
            APIResult<RequestUserDTO> apiResult = new APIResult<RequestUserDTO>();

            try
            {
                // 查询要修改的用户数据
                var userToUpdate = _db.Queryable<User>().Where(u => u.User_Id == requestUserDTO.User_Id).First();

                if (userToUpdate != null)
                {
                    // 更新用户信息
                    userToUpdate.User_Name = requestUserDTO.User_Name;
                    userToUpdate.U_Name = requestUserDTO.U_Name;
                    userToUpdate.User_Phone = requestUserDTO.User_Phone;
                    userToUpdate.User_PassWord= requestUserDTO.User_PassWord;
                    userToUpdate.Job_number= requestUserDTO.Job_number;
                    requestUserDTO.ids = string.Join(",", requestUserDTO.ids.Split(','));

                    // 使用 SqlSugar 的 Updateable 方法更新用户对象
                    _db.Updateable(userToUpdate).ExecuteCommand();

                    return new APIResult<RequestUserDTO>
                    {
                        Code = 200,
                        Data = requestUserDTO,
                        Message = "修改成功",
                        ids = _db.Insertable(userToUpdate).ExecuteCommand(),
                    };
                }
                else
                {
                    apiResult.Code = 404; // 用户不存在
                    apiResult.Message = "用户不存在，无法更新";
                }

                return apiResult;
            }
            catch (Exception ex)
            {
                apiResult.Code = 500; // 服务器内部错误
                apiResult.Message = "更新用户出错：" + ex.Message;
                return apiResult;
            }
        }

        /// <summary>
        /// 用户反填
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public APIResult<RequestUserDTO> GetUserSel(string userId)
        {
            APIResult<RequestUserDTO> apiResult = new APIResult<RequestUserDTO>();
            try
            {
                // 根据userId查询数据库中的User对象
                User user = _db.Queryable<User>().InSingle(userId);

                if (user != null)
                {
                    // 将查询到的User对象映射为RequestUserDTO对象
                    RequestUserDTO requestUserDTO = mapper.Map<RequestUserDTO>(user);


                    // 查询用户拥有的角色
                    List<Role> roles = _db.Queryable<Role, User_Role>((r, ur) => new JoinQueryInfos(
                            JoinType.Inner, r.RoleId.ToString() == ur.Role_Id))
                        .Where((r, ur) => ur.User_Id == userId)
                        .Select((r, ur) => r)
                        .ToList();

                    // 将角色信息填充到 ids 字段中
                    requestUserDTO.ids = string.Join(",", roles.Select(r => r.RoleId));

                    //// 设置复选框状态，假设复选框状态通过ids字段表示
                    //requestUserDTO.ids = !string.IsNullOrEmpty(requestUserDTO.ids) ? requestUserDTO.ids : ""; // 如果复选框选中，设置为相应的值；未选中则设置为空

                    return new APIResult<RequestUserDTO>
                    {
                        Code = 200,
                        Data = requestUserDTO,
                        Message = "反填成功",
                    };
                }
                else
                {
                    return new APIResult<RequestUserDTO>
                    {
                        Code = 400,
                        Data = null, // 或者其他处理方式，视情况而定
                        Message = "反填失败"
                    };
                }
            }
            catch (Exception ex)
            {
                // 异常处理逻辑
                throw new Exception("查询用户失败", ex);
            }
        }
    }
}
